package com.dhc.shiro.realm;

import com.dhc.shiro.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义Realm(未加密)
 */
public class PermissionRealm extends AuthorizingRealm {

    @Override
    public String getName() {
        return "PermissionRealm";
    }

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取到的是认证返回的info对象的第一个参数(即用户信息)
        User user = (User) principals.getPrimaryPrincipal();

        //去数据库查询此用户所拥有的角色和对应的权限
        //模拟数据库的角色集合
        List<String> roles = new ArrayList<>();
        //模拟数据库中的权限集合
        List<String> permissions = new ArrayList<>();
        roles.add("role1");
        permissions.add("user:update");
        //拥有所有权限但格式要一致
//        permissions.add("user:*");

        //把数据库获取的角色和权限封装在info中返回给realm进行处理
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;
    }










    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取页面传递的用户名
        String userName = (String) token.getPrincipal();
        //模拟数据库通过用户名查询
        User user = new User();
        user.setUsername("zhangsan");
        user.setPassword("123456");
        //用户名不同,即未查询到此用户名的用户信息,返回null,则报错未找到此用户
        if (!user.getUsername().equals(userName)) {
            return null;
        }
        //把数据库查询的信息封装为info传递给realm,在realm中比较info和token
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        return info;
    }
}
